/**
 * Created by jt on 2017/5/7.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";

import proInfoTpl from "./proInfo.handlebars";
import setTableTpl from "./set_table.handlebars";
import {currTyp,dpstFlg,pubPriFlg} from "../config.js";
jQuery(function () {
    App.init();
    var picFlag = true;
    var token = sessionStorage.getItem('token');
    if (token == null || token =='') {
        location.href = HOST_FRT+'/logins/login.html';
    }

    jQuery('.logOut').attr('href','../logins/login.html');
    var projId = getArgs().id;
    var sta = {
        "projId":projId,
        "bidDocSts":'01'
    };
    jQuery.ajax({
        url: HOST_ADDR+'/cpmp/bidProjOff/getTendSplrs',
        type: 'post',
        data: JSON.stringify(sta),
        dataType: 'json',
        contentType:"application/json",
        headers: {
            'access_token': token,'login_type':'ums'
        },
        success: function(resp){
            if (!resp.success) {
                console.log(resp.msgCod+' '+resp.msgInf);
                return;
            }
            console.log(resp);

            let infoHtml = proInfoTpl({chooseSup: resp.data});
            jQuery('.addMore').click(function () {
                $($('.form-actions')[0]).after(infoHtml);
            });
            
        },
        error:function(err){
            console.log(err);
        }
    });

    jQuery.ajax({
        url: HOST_ADDR+'/cpmp/bidProjOff/view/'+projId,
        type: 'get',
        // data: JSON.stringify(data),
        dataType: 'json',
        contentType:"application/json",
        headers: {
            'access_token': token,'login_type':'ums'
        },
        success: function(resp){
            if (!resp.success) {
                console.log(resp.msgCod+' '+resp.msgInf);
                return;
            }
            console.log(resp);

            //处理数据
            resp.data.bidProjOff.projNbrFmt = resp.data.bidProjOff.projNbr || '';
            resp.data.bidProjOff.bidOpenTimFmt = (new Date(resp.data.bidProjOff.bidOpenTim)).Format("yyyy-MM-dd hh:mm:ss") || '';
            resp.data.bidProjOff.bidEndTimFmt = (new Date(resp.data.bidProjOff.bidEndTim)).Format("yyyy-MM-dd hh:mm:ss") || '';
            resp.data.bidProjOff.currTypFmt = currTyp[resp.data.bidProjOff.currTyp] || '';
            resp.data.bidProjOff.dpstFlgFmt = dpstFlg[resp.data.bidProjOff.dpstFlg] || '';
            resp.data.bidProjOff.pubPriFlgFmt = pubPriFlg[resp.data.bidProjOff.pubPriFlg] || '';

            if(resp.data.matTypDesc!=null && resp.data.matTypDesc!=''){
                resp.data.bidProjOff.matTyp = resp.data.matTypDesc;
            }
            let tableHtml = setTableTpl(resp.data.bidProjOff);
            jQuery('.basicInfo').append(tableHtml);
            jQuery('.bidBok').html(resp.data.bidProjOff.bidBok);

        },
        error:function(err){
            alert(console.log);
        }
    });

    //提交审核
    jQuery('.subCheck').click(function () {
        var count = jQuery('.setSupplier').length;
        var setList=[];
        var atchDtos=[];  //附件
        // 附件
        let atchesObj = jQuery('#atches tr');
        for (let j = 0; j < atchesObj.length; j++) {
            atchDtos.push({
                "atchUrl": atchesObj.eq(j).attr('atchUrl'),
                "atchNam": atchesObj.eq(j).attr('atchNam')
            });
        }
        for (var i=0; i<count;i++){
            setList.push({
                "splrId":jQuery('.chooseSup').eq(i).val(),
                "matCod":jQuery('.matCod').eq(i).val(),
                "matNam":jQuery('.matNam').eq(i).val(),
                "pchsNum":jQuery('.pchsNum').eq(i).val(),
                "matUnt":jQuery('.matUnt').eq(i).val(),
                "awdAmt":jQuery('.awdAmt').eq(i).val()
            });
        }
        if (setList.length == 0) {
            alert('请填写项目定标供应商！');
            return;
        }
        var data = {
            "projId":projId,
            "ioBidProjOffAppAwdDtos":setList,
            "awdMemo": jQuery('.awdMemo').val(),
            "matReqBpmAppSeq": jQuery('.matReqBpmAppSeq').val(),
            "caseRept": jQuery('.caseRept').val(),
            "dept": jQuery('.dept').val(),
            "matReqDept": jQuery('.matReqDept').val(),
            "matPchsBgt": jQuery('.matPchsbgt').val(),
            "bidTolAmt": jQuery('.bidTolAmt').val(),
            "brfDesc": jQuery('.brfDesc').val(),
            "atchDtos": atchDtos
        };
        console.log(data);

        jQuery.ajax({
            url: HOST_ADDR+'/cpmp/bidProjOff/appAwd',
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            contentType:"application/json",
            headers: {
                'access_token': token,'login_type':'ums'
            },
            success: function(resp){
                if (!resp.success) {
                    alert(resp.msgCod+' '+resp.msgInf);
                    return;
                }
                console.log(resp)
                alert('申请定标成功！')
                location.href = 'proj_list.html';
            },
            error:function(err){
                console.log(err);
            }
        });

    });


//新增附件
    jQuery('.addFile').click(function () {
        jQuery('#atchFile').click();
        $("#atchFile").unbind().change(function(){
            picFlag = false;
            let formData = new FormData();
            let atchNam=$("#atchFile")[0].files[0].name;
            let atchUrl;
            formData.append('file', $("#atchFile")[0].files[0]);
            $.ajax({
                url: HOST_ADDR+'/cpmp/file/upload/atch',
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function(resp){
                    if(resp.success){
                        console.log(resp);
                        atchUrl = resp.data;
                        var atchUrlFmt = HOST_FILE + atchUrl;

                        let resultHtml = '<tr atchUrl="'+atchUrl+'" atchNam="'+atchNam+'">' +
                            '<td style="width: 80%; ">'+atchNam+'</td>' +
                            '<td style="width: 20%; ">' +
                            '<a class="btn mini green" target="_blank" href="'+atchUrlFmt+'"><i class="icon-download"></i> 下载</a>' +
                            '<a class="deleteAtch btn mini red" href="javascript:;"><i class="icon-trash"></i> 删除</a></td></tr>';
                        $('#atches').append(resultHtml);

                        //删除整行
                        jQuery('.deleteAtch').click(function () {
                            var _this = jQuery(this);
                            _this.parent('td').parent('tr').remove();
                        });

                    }else{
                        alert(resp.msgInf);
                    }
                },
                error:function(err){
                    alert('上传文件失败！');
                }
            });
        });
    });

});

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

